/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ixj.online.xml;

import ixj.online.process.Customer;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class CustomerXMLIOProcess {

    private String customerFolder;
    private static final String XML_VERSION_DEC = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";

    public CustomerXMLIOProcess(String customerFolder) {
        this.customerFolder = customerFolder;
    }

    public boolean save(Customer customer) {
        String id = UUID.randomUUID().toString();

        StringBuffer sb = new StringBuffer();
        sb.append(XML_VERSION_DEC).append("\n");
        sb.append("<customer>");
        sb.append("<id>").append(id).append("</id>");
        sb.append("<fname>").append(customer.getFirstName()).append("</fname>");
        sb.append("<email>").append(customer.getEmail()).append("</email>");
        sb.append("</customer>");

        String customerFile = this.customerFolder + id + ".xml";
        FileWriter fw = null;
        try {
            fw = new FileWriter(customerFile);
            BufferedWriter bw = new BufferedWriter(fw);

            //
            bw.write(sb.toString());
            bw.flush();

            return true;
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException ignore) {
                }
            }
        }
        return false;
    }

    public int count() {
        File f = new File(customerFolder);
        return f.listFiles().length;
    }
}
